/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.document.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.document.UploadFileDTO;
import com.je.document.exception.DocumentException;
import com.je.document.exception.DocumentExceptionEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * 本地文件存储工具类
 * <p>
 * 依赖 cn.hutool.core.io.FileUtil
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/8/29
 */
public class FileOperateLocalServiceImpl implements FileOperateService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 文件存储位置
     */
    private String basePath;
    /**
     * bucket修改时间
     */
    private Date modifiedTime;

    @Override
    public String getBasePath() {
        return basePath;
    }

    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }

    public Date getModifiedTime() {
        return modifiedTime;
    }

    public void setModifiedTime(Date modifiedTime) {
        this.modifiedTime = modifiedTime;
    }

    public FileOperateLocalServiceImpl(String tempDir, String basePath, Date modifiedTime) {
        //变量替换
        if (basePath.contains("@WebRoot@")) {
            String webRoot = tempDir;
            log.info("init--basePath-{},webroot-{}", webRoot);
            webRoot = webRoot.replaceAll("\\\\", "/");
            basePath = basePath.replaceAll("@WebRoot@", webRoot);
        }
        this.basePath = basePath;
        if (!FileUtil.exist(basePath)) {
            FileUtil.mkdir(this.basePath);
        }
        this.modifiedTime = modifiedTime;
    }

    @Override
    public UploadFileDTO uploadFile(String subfolder, String filePath, InputStream inputStream) {
        //真实路径
        String realFilePath = getRealFilePath(subfolder, filePath);
        //保存文件
        try {
            //写入文件
            FileUtil.writeFromStream(inputStream, realFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DocumentException(e.getMessage(), DocumentExceptionEnum.DOCUMENT_MANAGER_LOCAL_FILE_ERROR, e);
        }
        UploadFileDTO dto = new UploadFileDTO();
        //设置路径
        dto.setFilePath(realFilePath);
        return dto;
    }

    @Override
    public Boolean existFile(String subfolder, String filePath) {
        //真实路径
        String realFilePath = getRealFilePath(subfolder, filePath);
        return new File(realFilePath).exists();
    }

    @Override
    public InputStream readFile(String subfolder, String filePath) {
        //真实路径
        String realFilePath = getRealFilePath(subfolder, filePath);
        log.info("-------------realFilePath:" + realFilePath);
        try {
            return FileUtil.getInputStream(new File(realFilePath));
        } catch (Exception e) {
            e.printStackTrace();
            throw new DocumentException(e.getMessage(), DocumentExceptionEnum.DOCUMENT_MANAGER_LOCAL_FILE_ERROR, e);
        }
    }

    @Override
    public String getUrl(String subfolder,String filePath, Date expiration) {
        //获取指定有效期的访问地址
        return null;
    }

    @Override
    public boolean copy(String sourceFilePath, String targetFilePath) {
        return false;
    }

    @Override
    public boolean del(String bucket, String filePath) {
        if(Strings.isNullOrEmpty(filePath)){
            return false;
        }
        String realFilePath = getRealFilePath(bucket, filePath);
        try {
            return FileUtil.del(new File(realFilePath));
        } catch (Exception e) {
            e.printStackTrace();
            throw new DocumentException(e.getMessage(), DocumentExceptionEnum.DOCUMENT_MANAGER_LOCAL_FILE_ERROR, e);
        }
    }

    @Override
    public JSONArray listFilesMeta(String subfolder,String folder) {
        List<File> files = FileUtil.loopFiles(getRealFilePath(subfolder,folder));
        JSONArray resultArray = new JSONArray();
        JSONObject eachResult;
        for (File eachFile : files) {
            if (eachFile.isDirectory()) {
                JSONArray eachJSONArray = listFilesMeta(subfolder,folder + File.separator + eachFile.getName());
                resultArray.add(eachJSONArray);
                continue;
            }
            eachResult = new JSONObject();
            eachResult.put(KEY_META_FILE_NAME, eachFile.getName());
            eachResult.put(KEY_META_FILE_FULL_PATH, eachFile.getPath());
            eachResult.put(KEY_META_FILE_SIZE, eachFile.length());
            String suffix = null;
            if (eachFile.getName().lastIndexOf(".") > 0) {
                suffix = eachFile.getName().substring(eachFile.getName().lastIndexOf(".") + 1);
            }
            eachResult.put(KEY_META_FILE_SUFFIX, suffix);
            resultArray.add(eachResult);
        }
        return resultArray;
    }

    @Override
    public boolean isLastVersion(Date modifiedTime) {
        return DateUtil.isSameTime(modifiedTime, this.modifiedTime);
    }

    /**
     * 文件真实存储的路径
     *
     * @param filePath 数据库存储的路径
     * @return java.lang.String
     */
    private String getRealFilePath(String subfolder, String filePath) {
        //拼接基础路径
        if (StringUtils.isNotBlank(basePath)) {
            if (!FileUtil.exist(basePath + File.separator + subfolder)) {
                FileUtil.mkdir(basePath + File.separator + subfolder);
            }
            return basePath + File.separator + subfolder + filePath;
        }
        return File.separator + subfolder + filePath;
    }

}